<?php

namespace App\Http\Controllers\Api\Common;

use App\Http\Controllers\Api\CommonController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;

/**
 * Created by YiYuan Lin
 * Created at 18/12/10
 * Class UploadController
 * 上传文件公共接口
 * @package App\Http\Controllers\Api\Common
 */
class UploadController extends CommonController
{
    /**
     * @author YiYuan Lin
     * @date 18/12/10
     * @describe 上传图片接口
     */
    public function uploadPic(Request $request)
    {
        try {
            $params = [
                'file' => $request->file('file'),
            ];

            $rules = [
                'file' => 'required|file|image',
            ];

            $message = [
                'file.required' => '文件不得为空',
                'file.file' => '请上传文件',
                'file.image' => '文件必须为图片格式（ jpeg、png、bmp、gif、或 svg ）'
            ];

            $this->verifyParams($params,$rules,$message);

            $file = $params['file'];

//            dd($params['file']);

            //得到源文件名
            $originalName = $file->getClientOriginalName();

            // 得到上传文件的后缀
            $ext = $file->getClientOriginalExtension();

            // 得到上传文件的tmp绝对路径
            $realPath = $file->getRealPath();


            if ($file->getSize() > 30000000) {
                 $this->throwExp('上传图片尺寸过大');
            }

            $flieName = date('Y-m-d-H-i-s') . '/' . md5(uniqid())  . '.' . $ext;


            //上传图片到七牛云
            $bool = Storage::disk('qiniu')->put($flieName,file_get_contents($realPath));

            if ($bool) {
                return $this->successReturn(200,env('QINIU_DEFAULT').$flieName);
            }else{
                $this->throwExp('上传文件失败');
            }


        } catch(\Exception $e) {
            return $this->errorReturn(500, $e->getMessage());
        }
    }
}
